package ar.edu.itba.it.pdc.httpParser.models;

import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import ar.edu.itba.it.pdc.httpParser.interfaces.Model;
import ar.edu.itba.it.pdc.nio.ByteBufferPool;
import ar.edu.itba.it.pdc.nio.MemoryAllocationLimitHited;

public class HttpBody implements Model{

	List<Token> tokens = new LinkedList<Token>();

	public void append(Token token){
		tokens.add(token);
	}
	
	
	@Override
	public void appendByteBuffers(Queue<ByteBuffer> queue) throws MemoryAllocationLimitHited {
		ByteBuffer byteBuffer  = ByteBufferPool.getInstance().getByteBuffer();

		for (Token token : tokens) {
			for (byte b : token.getName()) {
				byteBuffer.put(b);
				if (byteBuffer.remaining() == 0) {
					byteBuffer.flip();
					queue.add(byteBuffer);
					byteBuffer  = ByteBufferPool.getInstance().getByteBuffer();
				}
			}
		}
		
		if (byteBuffer.position() != 0) {
			byteBuffer.flip();
			queue.add(byteBuffer);
		} else {
			ByteBufferPool.getInstance().retriveByteBuffer(byteBuffer);
		}
	}
	
	public List<Token> getTokens() {
		return tokens;
	}
	
	public void setTokens(List<Token> tokens) {
		this.tokens = tokens;
	}
}